package com.jiawa.wiki.service;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiawa.wiki.domain.Ebook;
import com.jiawa.wiki.domain.EbookExample;
import com.jiawa.wiki.mapper.EbookMapper;
import com.jiawa.wiki.req.EbookQueryReq;
import com.jiawa.wiki.resp.EbookResp;
import com.jiawa.wiki.resp.PageResp;
import com.jiawa.wiki.util.CopyUtil;
import com.jiawa.wiki.util.SnowFlake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class EbookService {

    @Resource
    public EbookMapper ebookMapper;

    @Resource
    public SnowFlake snowFlake;

    private final static Logger LOG = LoggerFactory.getLogger(EbookService.class);

    public PageResp<EbookResp> getlist(EbookQueryReq req){
        //ctrl+alt+v
        EbookExample ebookExample = new EbookExample();
        EbookExample.Criteria criteria = ebookExample.createCriteria();

        //名称模糊匹配查询
        if (!ObjectUtils.isEmpty(req.getName())){
            criteria.andNameLike("%"+req.getName()+"%");
        }

        //精准匹配categoryId2,查出对应电子书
        if (!ObjectUtils.isEmpty(req.getCategoryId2())){
            criteria.andCategory2IdEqualTo(req.getCategoryId2());
        }

        PageHelper.startPage(req.getPage(),req.getSize());

        //处理响应数据
        //存完整数据的列表
        List<Ebook> ebookList = ebookMapper.selectByExample(ebookExample);

        PageInfo<Ebook> pageInfo = new PageInfo<>(ebookList);
        LOG.info("总行数：{}",pageInfo.getTotal());
        LOG.info("总页数：{}",pageInfo.getPages());

        List<EbookResp>list = CopyUtil.copyList(ebookList,EbookResp.class);

        PageResp<EbookResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);

        return pageResp;


        //return ebookMapper.selectByExample(null);

    }

    public void save(EbookQueryReq req){

        Ebook ebook=CopyUtil.copy(req, Ebook.class);

        if(!ObjectUtils.isEmpty(req.getId())) {
           //更新
           ebookMapper.updateByPrimaryKey(ebook);
        } else {
            //新增
            ebook.setId(snowFlake.nextId());
            ebookMapper.insert(ebook);
        }

    }

    //删除
    public void delete(long id){
        ebookMapper.deleteByPrimaryKey(id);

    }


}